<template>
  <div class="bottom-r">
    <div class="control-panel">
      <div class="panel-title">{{ t('game.controlPanel.console') }}</div>
      <!-- 录音 -->
      <div class="panel-section">
        <div class="panel-row">
          <div class="u-f-ac u-f-c icon-row">
            <i class="panel-icon u-f-ajc iconfont icon-luyin"></i>
            <span class="jishi">{{ t('game.controlPanel.recording') }}</span>
          </div>
          <div>
            <div class="panel-time">{{ recordTime }}</div>
            <div class="u-f-ajsb" style="padding: 0 10px;">
              <template v-if="!isRecording && !currentItemAudio">
                <button class="panel-btn" disabled>{{ t('game.controlPanel.playRecording') }}</button>
                <button class="panel-btn primary" @click="startRecord">{{ t('game.controlPanel.startRecording') }}</button>
              </template>
              <template v-else-if="isRecording">
                <button class="panel-btn" @click="cancelRecord">{{ t('game.controlPanel.cancelRecording') }}</button>
                <button class="panel-btn primary" @click="onFinishRecord">{{ t('game.controlPanel.finishRecording') }}</button>
              </template>
              <template v-else>
                <button class="panel-btn" @click="playAudio">{{ t('game.controlPanel.playRecording') }}</button>
                <button class="panel-btn primary" @click="startRecord">{{ t('game.controlPanel.reRecord') }}</button>
              </template>
            </div>
          </div>
        </div>
      </div>
      <!-- 计时器 -->
      <div class="panel-section">
        <div class="panel-row">
          <div class="u-f-ac u-f-c icon-row">
            <i class="panel-icon u-f-ajc iconfont icon-jishiqi"></i>
            <span class="jishi">{{ t('game.controlPanel.timer') }}</span>
          </div>
          <div>
            <div class="panel-time">{{ timerTime }}</div>
            <div class="u-f-ajsb" style="padding: 0 10px;">
              <button class="panel-btn" @click="resetTimer">{{ t('game.controlPanel.reset') }}</button>
              <button class="panel-btn primary" @click="toggleTimer">{{ timerRunning ? t('game.controlPanel.pause') : t('game.controlPanel.start') }}</button>
            </div>
          </div>
        </div>
      </div>
      <!-- 闹钟 -->
      <div class="panel-section">
        <div class="panel-row">
          <div class="u-f-ac u-f-c icon-row">
            <i class="panel-icon u-f-ajc iconfont icon-daochu-01"></i>
            <span class="jishi">{{ t('game.controlPanel.alarm') }}</span>
          </div>
          <div>
            <div class="panel-time2" v-if="!alarmRunning && !alarmFinished && !alarmPaused">
              <input type="text" v-model="formattedAlarmHours" maxlength="2" class="alarm-input" :disabled="alarmRunning || alarmFinished || alarmPaused" @input="validateNumberInput($event, 0, 23, 'hours')" /> :
              <input type="text" v-model="formattedAlarmMinutes" maxlength="2" class="alarm-input" :disabled="alarmRunning || alarmFinished || alarmPaused" @input="validateNumberInput($event, 0, 59, 'minutes')" /> :
              <input type="text" v-model="formattedAlarmSeconds" maxlength="2" class="alarm-input" :disabled="alarmRunning || alarmFinished || alarmPaused" @input="validateNumberInput($event, 0, 59, 'seconds')" />
            </div>
            <div class="panel-time" v-else>{{ alarmTime }}</div>
            <div class="u-f-ajsb" style="padding: 0 10px;">
              <button class="panel-btn" @click="resetAlarm">{{ alarmFinished ? t('game.controlPanel.closeAlarm') : t('game.controlPanel.reset') }}</button>
              <button class="panel-btn primary" @click="toggleAlarm" :disabled="alarmFinished">{{ getAlarmButtonText() }}</button>
            </div>
          </div>
        </div>
      </div>
      <!-- 计数器 -->
      <div class="panel-section" style="border-bottom: none;padding-top: 10px;padding-bottom: 10px;">
        <div class="panel-row">
          <div class="u-f-ac u-f-c icon-row">
            <i class="panel-icon u-f-ajc iconfont icon-kanbansheji-jishuqi"></i>
            <span class="jishi">{{ t('game.controlPanel.counter') }}</span>
          </div>
          <div>
            <div class="counter-group">
              <div class="counter-label">{{ t('game.controlPanel.correct') }}</div>
              <button class="counter-btn" @click="counterCorrect > 0 && counterCorrect--">&lt;</button>
              <span class="counter-value">{{ counterCorrect }}</span>
              <button class="counter-btn" @click="counterCorrect++">&gt;</button>
            </div>
            <div class="counter-group">
              <div class="counter-label">{{ t('game.controlPanel.wrong') }}</div>
              <button class="counter-btn" @click="counterWrong > 0 && counterWrong--">&lt;</button>
              <span class="counter-value">{{ counterWrong }}</span>
              <button class="counter-btn" @click="counterWrong++">&gt;</button>
            </div>
            <div class="counter-group">
              <div class="counter-label">{{ t('game.controlPanel.missed') }}</div>
              <button class="counter-btn" @click="counterMiss > 0 && counterMiss--">&lt;</button>
              <span class="counter-value">{{ counterMiss }}</span>
              <button class="counter-btn" @click="counterMiss++">&gt;</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, defineEmits, defineExpose, defineProps, onMounted, ref, watch } from 'vue'
import naozhongMp3 from '../../../assets/mp3/naozhong.mp3'

// 翻译系统
const translationVersion = ref(0)
let t = (key: any, params?: any) => {
	const keys = key.split('.')
	let current: any = translations.value
	for (const k of keys) {
		if (current && typeof current === 'object') {
			current = current[k]
		} else {
			return key
		}
	}
	if (typeof current === 'string' && params) {
		return current.replace(/\{(\w+)\}/g, (match: any, key: any) => params[key] || match)
	}
	return current || key
}

const translations = ref<any>({})

async function initTranslations() {
	try {
		const currentLang = localStorage.getItem('language') || 'zh-CN'
		let langModule
		if (currentLang === 'en-US') {
			langModule = await import('../../../i18n/locales/en-US')
		} else {
			langModule = await import('../../../i18n/locales/zh-CN')
		}
		translations.value = langModule.default
		translationVersion.value++
	} catch (error) {
		console.error('Failed to load translations:', error)
	}
}

const props = defineProps<{
  currentItemAudioProp?: string
  currentItemProp?: any
}>()
// 录音
const isRecording = ref(false)
const recordTime = ref('00 : 00 : 00')
let recordTimer: any = null
let recordSec = 0
const audioUrl = ref('')
const currentItemAudio = ref('')
let mediaRecorder: any = null

// 监听当前题目录音变化
watch(() => props.currentItemAudioProp, (newAudio, oldAudio) => {
  console.log('watch - props变化:', {
    old: oldAudio,
    new: newAudio,
    isRecording: isRecording.value
  })
  
  currentItemAudio.value = newAudio || ''
  if (!isRecording.value) {
    if (newAudio) {
      audioUrl.value = newAudio
      // 优先使用保存的录音时长，如果没有再从音频获取
      const savedDuration = props.currentItemProp?.recordDuration
      if (savedDuration && savedDuration > 0) {
        recordSec = savedDuration
        recordTime.value = formatTime(recordSec)
        console.log('watch - 使用保存的录音时长:', recordSec)
      } else {
        // 如果没有保存的时长，从音频获取
        if (newAudio.startsWith('blob:')) {
          const audio = new Audio(newAudio)
          audio.addEventListener('loadedmetadata', () => {
            if (audio.duration && isFinite(audio.duration)) {
              recordSec = Math.floor(audio.duration)
              recordTime.value = formatTime(recordSec)
              console.log('watch - 从音频获取录音时长:', recordSec)
            }
          })
          // 添加错误处理，确保即使音频加载失败也能显示时长
          audio.addEventListener('error', () => {
            console.warn('音频加载失败，使用默认时长显示')
            if (recordSec > 0) {
              recordTime.value = formatTime(recordSec)
            }
          })
        } else {
          // 对于非blob URL，尝试获取时长
          const audio = new Audio(newAudio)
          audio.addEventListener('loadedmetadata', () => {
            if (audio.duration && isFinite(audio.duration)) {
              recordSec = Math.floor(audio.duration)
              recordTime.value = formatTime(recordSec)
              console.log('watch - 从非blob音频获取录音时长:', recordSec)
            }
          })
        }
      }
    } else {
      audioUrl.value = ''
      recordSec = 0
      recordTime.value = '00 : 00 : 00'
      console.log('watch - 清空录音状态')
    }
  }
}, { immediate: true })

// 监听当前题目变化，恢复录音时长
watch(() => props.currentItemProp, (newItem, oldItem) => {
  console.log('watch - 题目变化:', {
    old: oldItem?.title || oldItem?.questionType,
    new: newItem?.title || newItem?.questionType,
    isRecording: isRecording.value,
    savedDuration: newItem?.recordDuration
  })
  
  if (!isRecording.value && newItem) {
    // 恢复保存的录音时长
    if (newItem.recordDuration && newItem.recordDuration > 0) {
      recordSec = newItem.recordDuration
      recordTime.value = formatTime(recordSec)
      console.log('watch - 恢复录音时长:', recordSec)
    } else if (!newItem.audio) {
      // 如果没有录音也没有保存的时长，重置为0
      recordSec = 0
      recordTime.value = '00 : 00 : 00'
      console.log('watch - 重置录音时长')
    }
  }
}, { immediate: true })

let audioChunks: any[] = []
let backupAudioUrl = '' // 备份录音URL
let backupRecordSec = 0 // 备份录音时长
const emit = defineEmits(['recorded', 'recording-cancelled'])
function startRecord() {
  // 备份当前录音（如果存在）
  console.log('startRecord - 开始录音前的状态:')
  console.log('audioUrl.value:', audioUrl.value)
  console.log('currentItemAudio.value:', currentItemAudio.value)
  console.log('props.currentItemAudioProp:', props.currentItemAudioProp)
  
  // 确保备份真实的录音数据
  const realAudio = props.currentItemAudioProp || currentItemAudio.value || audioUrl.value
  if (realAudio) {
    backupAudioUrl = realAudio
    backupRecordSec = recordSec
    console.log('备份录音:', backupAudioUrl)
    console.log('备份时长:', backupRecordSec)
  } else {
    console.log('没有录音需要备份')
    backupAudioUrl = ''
    backupRecordSec = 0
  }
  
  recordSec = 0
  recordTime.value = '00 : 00 : 00'
  audioUrl.value = '' // 清空当前显示的录音
  audioChunks = []
  // 清除之前的播放计时器
  if (window.__playTimer) {
    clearInterval(window.__playTimer)
    window.__playTimer = null
  }
  
  // 检查录音设备权限和可用性
  navigator.mediaDevices.getUserMedia({ audio: true })
    .then(stream => {
      mediaRecorder = new window.MediaRecorder(stream)
      mediaRecorder.start()
      mediaRecorder.ondataavailable = (e: any) => audioChunks.push(e.data)
      mediaRecorder.onstop = () => {
        const blob = new Blob(audioChunks)
        audioUrl.value = URL.createObjectURL(blob)
      }
      isRecording.value = true
      recordTimer = setInterval(() => {
        recordSec++
        recordTime.value = formatTime(recordSec)
      }, 1000)
    })
    .catch(error => {
      console.error('录音设备访问失败:', error)
      
      // 根据错误类型显示不同的提示信息
      let errorMessage = t('game.controlPanel.noRecordingDevice')
      
      if (error.name === 'NotAllowedError') {
        errorMessage = t('game.controlPanel.permissionDenied')
      } else if (error.name === 'NotFoundError') {
        errorMessage = t('game.controlPanel.noRecordingDevice')
      } else if (error.name === 'NotReadableError') {
        errorMessage = t('game.controlPanel.deviceOccupied')
      } else if (error.name === 'OverconstrainedError') {
        errorMessage = t('game.controlPanel.deviceNotSuitable')
      } else if (error.name === 'TypeError') {
        errorMessage = t('game.controlPanel.deviceConfigError')
      }
      
      // 显示错误弹窗
      showErrorDialog(errorMessage)
    })
}
function stopRecordExpose(): Promise<string> {
  return new Promise<string>((resolve) => {
    if (isRecording.value) {
      if (mediaRecorder && mediaRecorder.state === 'recording') {
        mediaRecorder.onstop = () => {
          const blob = new Blob(audioChunks)
          audioUrl.value = URL.createObjectURL(blob)
          isRecording.value = false
          clearInterval(recordTimer)
          // 保持recordSec不重置，保存录音时长
          resolve(audioUrl.value)
        }
        mediaRecorder.stop()
      } else {
        isRecording.value = false
        clearInterval(recordTimer)
        resolve(audioUrl.value)
      }
    } else {
      // 如果没有在录音，返回空字符串，避免把旧录音保存到新题目
      resolve('')
    }
  })
}
function onFinishRecord() {
  stopRecordExpose().then(audio => {
    // 录音成功完成，清除备份
    backupAudioUrl = ''
    backupRecordSec = 0
    // 更新当前录音状态
    currentItemAudio.value = audio
    
    // 通知父组件录音完成，父组件会保存到题目对象
    emit('recorded', audio)
    console.log('录音完成，新录音URL:', audio)
  })
}
function playAudio() {
  if (audioUrl.value) {
    console.log('=== 开始播放音频 ===')
    console.log('当前recordSec:', recordSec, 'recordTime.value:', recordTime.value)
    const audio = new Audio(audioUrl.value)
    let playTimer: any = null
    let originalDuration = recordSec // 保存原始录音时长
    let isPlaying = false // 添加播放状态标记
    
    console.log('保存的originalDuration:', originalDuration)
    
    if (window.__playTimer) {
      clearInterval(window.__playTimer)
      window.__playTimer = null
    }
    audio.currentTime = 0
    
    // 先获取音频时长，但优先使用已保存的时长
    audio.addEventListener('loadedmetadata', () => {
      console.log('loadedmetadata事件触发 - isPlaying:', isPlaying, 'audio.duration:', audio.duration)
      if (audio.duration && isFinite(audio.duration) && audio.duration > 0) {
        const audioDuration = Math.floor(audio.duration)
        console.log('音频时长检查 - originalDuration:', originalDuration, 'audioDuration:', audioDuration)
        // 如果没有保存的时长或保存的时长不准确，使用音频实际时长
        if (originalDuration === 0 || Math.abs(originalDuration - audioDuration) > 2) {
          originalDuration = audioDuration
          console.log('更新originalDuration为:', originalDuration)
          // 只在未播放时更新显示，避免覆盖倒计时
          if (!isPlaying) {
            recordSec = originalDuration
            recordTime.value = formatTime(recordSec)
            console.log('未播放状态，更新显示为:', formatTime(recordSec))
          } else {
            console.log('播放中，跳过显示更新以避免覆盖倒计时')
          }
        }
      }
    })
    
    // 开始播放时启动计时器
    audio.addEventListener('play', () => {
      isPlaying = true // 标记为播放状态
      console.log('播放开始 - isPlaying设置为true, originalDuration:', originalDuration)
      playTimer = setInterval(() => {
        // 使用保存的录音时长而不是audio.duration，因为blob URL的duration可能不准确
        if (originalDuration > 0) {
          const currentTime = audio.currentTime
          const remain = originalDuration - currentTime
          const remainCeil = Math.ceil(remain > 0 ? remain : 0)
          console.log('播放倒计时 - currentTime:', currentTime.toFixed(2), 'originalDuration:', originalDuration, 'remain:', remain.toFixed(2), 'remainCeil:', remainCeil, 'recordTime将设置为:', formatTime(remainCeil))
          // 播放时显示剩余时间倒计时
          recordTime.value = formatTime(remainCeil)
          
          if (remain <= 0.1 || audio.ended || currentTime >= originalDuration) {
            console.log('播放结束 - remain:', remain, 'audio.ended:', audio.ended, 'currentTime >= originalDuration:', currentTime >= originalDuration)
            clearInterval(playTimer)
            window.__playTimer = null
            isPlaying = false
            // 播放结束后恢复显示总时长
            recordSec = originalDuration
            recordTime.value = formatTime(originalDuration)
            console.log('播放结束后恢复总时长:', originalDuration)
          }
        }
      }, 100)
      window.__playTimer = playTimer
    })
    
    audio.addEventListener('ended', () => {
      console.log('ended事件触发')
      if (playTimer) {
        clearInterval(playTimer)
        window.__playTimer = null
      }
      isPlaying = false
      // 播放结束后显示录音的实际时长
      recordSec = originalDuration
      recordTime.value = formatTime(recordSec)
      console.log('ended事件处理完成，恢复总时长:', originalDuration)
    })
    
    audio.addEventListener('pause', () => {
      console.log('pause事件触发')
      if (playTimer) {
        clearInterval(playTimer)
        window.__playTimer = null
      }
      isPlaying = false
      // 暂停时也恢复显示总时长
      recordSec = originalDuration
      recordTime.value = formatTime(recordSec)
      console.log('pause事件处理完成，恢复总时长:', originalDuration)
    })
    
    audio.play()
  }
}
function cancelRecord() {
  isRecording.value = false
  clearInterval(recordTimer)
  
  console.log('cancelRecord - 取消录音时的状态:')
  console.log('backupAudioUrl:', backupAudioUrl)
  console.log('backupRecordSec:', backupRecordSec)
  
  // 如果有备份录音，恢复备份
  if (backupAudioUrl) {
    console.log('恢复备份录音:', backupAudioUrl)
    console.log('备份时长值:', backupRecordSec)
    
    const restoreAudioUrl = backupAudioUrl
    const restoreRecordSec = backupRecordSec
    
    // 先清除备份，避免重复使用
    backupAudioUrl = ''
    backupRecordSec = 0
    
    audioUrl.value = restoreAudioUrl
    currentItemAudio.value = restoreAudioUrl // 同步更新当前录音状态
    
    // 先使用备份时长，等音频加载完成后再更新
    recordSec = restoreRecordSec
    recordTime.value = formatTime(recordSec)
    console.log('立即设置备份时长:', recordSec)
    
    // 重新获取音频实际时长，确保显示正确
    const audio = new Audio(restoreAudioUrl)
    audio.addEventListener('loadedmetadata', () => {
      if (audio.duration && isFinite(audio.duration) && audio.duration > 0) {
        recordSec = Math.floor(audio.duration)
        recordTime.value = formatTime(recordSec)
        console.log('恢复录音时长(从音频):', recordSec)
      } else {
        // 如果无法获取时长，使用备份值
        recordSec = restoreRecordSec
        recordTime.value = formatTime(recordSec)
        console.log('使用备份时长:', recordSec)
      }
    })
    
    // 通知父组件恢复录音
    emit('recording-cancelled', restoreAudioUrl)
  } else {
    console.log('没有备份录音，清空状态')
    audioUrl.value = ''
    recordSec = 0
    recordTime.value = '00 : 00 : 00'
    currentItemAudio.value = ''
    // 通知父组件没有录音
    emit('recording-cancelled', '')
  }
  
  // 最后停止录音器，避免覆盖已恢复的录音
  if (mediaRecorder && mediaRecorder.state === 'recording') {
    // 临时移除onstop事件处理，避免覆盖恢复的录音
    const originalOnStop = mediaRecorder.onstop
    mediaRecorder.onstop = null
    mediaRecorder.stop()
    console.log('已停止录音器，避免覆盖恢复的录音')
    // 恢复原有的onstop处理（虽然这里可能不需要）
    setTimeout(() => {
      if (mediaRecorder) {
        mediaRecorder.onstop = originalOnStop
      }
    }, 100)
  }
  
  // 清除播放计时器
  if (window.__playTimer) {
    clearInterval(window.__playTimer)
    window.__playTimer = null
  }
}
function cancelRecordingSilently() {
  if (isRecording.value) {
    console.log('开始取消录音...')
    
    // 立即停止录音状态
    isRecording.value = false
    clearInterval(recordTimer)
    recordTimer = null
    
    // 停止录音器
    if (mediaRecorder && mediaRecorder.state === 'recording') {
      console.log('停止MediaRecorder')
      // 移除onstop事件处理，避免创建blob
      mediaRecorder.onstop = null
      mediaRecorder.ondataavailable = null
      mediaRecorder.stop()
      
      // 停止媒体流
      if (mediaRecorder.stream) {
        mediaRecorder.stream.getTracks().forEach((track: MediaStreamTrack) => track.stop())
      }
    }
    
    // 清空录音状态和数据
    recordSec = 0
    recordTime.value = '00 : 00 : 00'
    audioUrl.value = ''
    currentItemAudio.value = ''
    audioChunks = []
    
    // 清除备份数据
    backupAudioUrl = ''
    backupRecordSec = 0
    
    // 清除播放计时器
    if (window.__playTimer) {
      clearInterval(window.__playTimer)
      window.__playTimer = null
    }
    
    console.log('录音已完全取消，所有状态已清空')
  }
}
// 计时器
const timerTime = ref('00 : 00 : 00')
let timerSec = 0
let timerInterval: any = null
const timerRunning = ref(false)
function toggleTimer() {
  if (!timerRunning.value) {
    timerRunning.value = true
    timerInterval = setInterval(() => {
      timerSec++
      timerTime.value = formatTime(timerSec)
    }, 1000)
  } else {
    timerRunning.value = false
    clearInterval(timerInterval)
  }
}
function resetTimer() {
  timerRunning.value = false
  clearInterval(timerInterval)
  timerSec = 0
  timerTime.value = '00 : 00 : 00'
}
// 闹钟
const alarmHours = ref(0)
const alarmMinutes = ref(0)
const alarmSeconds = ref(0)

// 格式化显示的计算属性
const formattedAlarmHours = computed({
  get: () => String(alarmHours.value).padStart(2, '0'),
  set: (val) => alarmHours.value = Number(val) || 0
})
const formattedAlarmMinutes = computed({
  get: () => String(alarmMinutes.value).padStart(2, '0'),
  set: (val) => alarmMinutes.value = Number(val) || 0
})
const formattedAlarmSeconds = computed({
  get: () => String(alarmSeconds.value).padStart(2, '0'),
  set: (val) => alarmSeconds.value = Number(val) || 0
})

// 验证数字输入
function validateNumberInput(event: any, min: number, max: number, type: string) {
  const value = event.target.value
  // 只允许数字
  const numericValue = value.replace(/[^0-9]/g, '')
  
  if (numericValue !== value) {
    event.target.value = numericValue
  }
  
  // 验证范围
  const num = parseInt(numericValue) || 0
  if (num > max) {
    const maxStr = String(max).padStart(2, '0')
    event.target.value = maxStr
    if (type === 'hours') alarmHours.value = max
    else if (type === 'minutes') alarmMinutes.value = max
    else if (type === 'seconds') alarmSeconds.value = max
  } else if (num < min) {
    const minStr = String(min).padStart(2, '0')
    event.target.value = minStr
    if (type === 'hours') alarmHours.value = min
    else if (type === 'minutes') alarmMinutes.value = min
    else if (type === 'seconds') alarmSeconds.value = min
  }
}
const alarmTime = ref('00 : 00 : 00')
let alarmInterval: any = null
const alarmRunning = ref(false)
const alarmFinished = ref(false)
const alarmPaused = ref(false) // 添加暂停状态
let alarmRemain = 0
let alarmAudio: HTMLAudioElement | null = null
function getAlarmButtonText() {
  if (alarmRunning.value) {
    return t('game.controlPanel.pause')
  } else if (alarmPaused.value) {
    return t('game.controlPanel.continue') || '继续'
  } else {
    return t('game.controlPanel.start')
  }
}

function toggleAlarm() {
  if (!alarmRunning.value && !alarmFinished.value && !alarmPaused.value) {
    // 开始新的倒计时
    alarmRemain = Number(alarmHours.value) * 3600 + Number(alarmMinutes.value) * 60 + Number(alarmSeconds.value)
    if (alarmRemain <= 0) return
    alarmRunning.value = true
    alarmPaused.value = false
    alarmTime.value = formatTime(alarmRemain)
    alarmInterval = setInterval(() => {
      alarmRemain--
      alarmTime.value = formatTime(alarmRemain)
      if (alarmRemain <= 0) {
        clearInterval(alarmInterval)
        alarmRunning.value = false
        alarmFinished.value = true
        alarmPaused.value = false
        alarmTime.value = formatTime(0)
        if (!alarmAudio) {
          alarmAudio = new Audio(naozhongMp3)
          alarmAudio.loop = true
        }
        alarmAudio.currentTime = 0
        alarmAudio.play()
      }
    }, 1000)
  } else if (alarmRunning.value) {
    // 暂停倒计时
    alarmRunning.value = false
    alarmPaused.value = true
    clearInterval(alarmInterval)
  } else if (alarmPaused.value) {
    // 继续倒计时
    alarmRunning.value = true
    alarmPaused.value = false
    alarmInterval = setInterval(() => {
      alarmRemain--
      alarmTime.value = formatTime(alarmRemain)
      if (alarmRemain <= 0) {
        clearInterval(alarmInterval)
        alarmRunning.value = false
        alarmFinished.value = true
        alarmPaused.value = false
        alarmTime.value = formatTime(0)
        if (!alarmAudio) {
          alarmAudio = new Audio(naozhongMp3)
          alarmAudio.loop = true
        }
        alarmAudio.currentTime = 0
        alarmAudio.play()
      }
    }, 1000)
  }
}
function resetAlarm() {
  clearInterval(alarmInterval)
  if (alarmFinished.value) {
    alarmFinished.value = false
    if (alarmAudio) {
      alarmAudio.pause()
      alarmAudio.currentTime = 0
    }
  }
  alarmRunning.value = false
  alarmPaused.value = false
  alarmHours.value = 0
  alarmMinutes.value = 0
  alarmSeconds.value = 0
  alarmTime.value = '00 : 00 : 00'
}
// 计数器
const counterCorrect = ref(0)
const counterWrong = ref(0)
const counterMiss = ref(0)

// 错误弹窗相关
function showErrorDialog(message: string) {
  window.messageRef?.show(message,'error')
}

function formatTime(sec: number) {
  const h = String(Math.floor(sec / 3600)).padStart(2, '0')
  const m = String(Math.floor((sec % 3600) / 60)).padStart(2, '0')
  const s = String(sec % 60).padStart(2, '0')
  return `${h} : ${m} : ${s}`
}
// 计时器和闹钟重置
function resetTimers() {
  // 重置计时器
  timerRunning.value = false
  clearInterval(timerInterval)
  timerSec = 0
  timerTime.value = '00 : 00 : 00'
  // 重置闹钟
  clearInterval(alarmInterval)
  if (alarmFinished.value) {
    alarmFinished.value = false
    if (alarmAudio) {
      alarmAudio.pause()
      alarmAudio.currentTime = 0
    }
  }
  alarmRunning.value = false
  alarmPaused.value = false
  alarmHours.value = 0
  alarmMinutes.value = 0
  alarmSeconds.value = 0
  alarmTime.value = '00 : 00 : 00'
  // 不重置录音时间显示，因为录音时间需要保持
  // recordSec = 0
  // recordTime.value = '00 : 00 : 00'
  // 清除播放计时器
  if (window.__playTimer) {
    clearInterval(window.__playTimer)
    window.__playTimer = null
  }
}

onMounted(async () => {
  // 初始化翻译
  await initTranslations()
})

defineExpose({
  stopRecord: stopRecordExpose,
  resetTimers,
  isRecording,
  recordSec: () => recordSec,
  cancelRecordingSilently,
  getIsRecording: () => isRecording.value
})
declare global {
  interface Window {
    __playTimer?: any
    messageRef?: {
      show: (msg: string, type?: string) => void
    }
  }
}
</script>

<style scoped>
.bottom-r {
  width: 100%;
  background: #f3f7fa;
  border-radius: 16px;
  box-shadow: 0 2px 8px #f0f3fa;
  margin-top: 18px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.control-panel {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.panel-title {
  background: var(--theme-primary);
  color: #fff;
  font-size: 24px;
  font-weight: bold;
  border-radius: 16px 16px 0 0;
  padding: 3px 0;
  text-align: center;
  width: 100%;
  letter-spacing: 2px;
}
.panel-section {
  border-radius: 12px;
  margin: 0px 0 0 0;
  padding: 15px 18px 15px 18px;
  width: 92%;
  display: flex;
  flex-direction: column;
  align-items: center;
  border-bottom: #fff solid 1px;
}
.panel-row {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  justify-content: flex-start;
}
.panel-icon {
  margin-bottom: 8px;
  font-size: 32px;
  color: var(--theme-primary);
  width: 38px;
  text-align: center;
  background-color: #fff;
  border-radius: 50%;
  width: 70px;
  height: 70px;
}
.panel-time {
  font-size: 15px;
  background: #fff;
  border-radius: 22px;
  padding: 3px 30px;
  margin: 0 8px;
  border: 1px solid #e0e0e0;
  min-width: 160px;
  text-align: center;
  margin-bottom: 10px;
  letter-spacing: 0.4em;
  width: 70%;
  color: #333;
  font-size: 15px;
}
.panel-time2 {
  font-size: 15px;
  background: #fff;
  border-radius: 22px;
  padding: 3px 30px;
  margin: 0 8px;
  border: 1px solid #e0e0e0;
  min-width: 160px;
  text-align: center;
  margin-bottom: 10px;
  width: 70%;
}
.panel-btn {
  background: #fefefe;
  color: #333;
  border: none;
  border-radius: 8px;
  padding: 6px 18px;
  font-size: 15px;
  cursor: pointer;
  min-width: 100px;
  transition: background 0.2s, color 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.panel-btn.primary {
  background: var(--theme-primary);
  color: #fff;
}
.panel-btn:disabled {
  background: #e0e0e0;
  color: #bbb;
  cursor: not-allowed;
}
.panel-label {
  color: #888;
  font-size: 15px;
  margin-top: 8px;
  text-align: left;
  width: 100%;
  padding-left: 38px;
}
.counter-row {
  gap: 24px;
}
.counter-group {
  display: flex;
  align-items: center;
  gap: 6px;
  width: 220px;
  margin-bottom: 2px !important;
  border-radius: 8px;
  padding: 4px 10px;
  margin: 0 6px;
}
.counter-label {
  color: #333;
  font-size: 15px;
  margin-right: 3px;
}
.counter-btn {
  background: #fff;
  color: #888;
  border: none;
  border-radius: 6px;
  padding: 2px 10px;
  font-size: 18px;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}
.counter-value {
  font-size: 18px;
  color: #222;
  background-color: #fff;
  border-radius: 16px;
  margin: 0 6px;
  width: 80px;
  min-width: 24px;
  text-align: center;
  display: inline-block;
}
.alarm-input {
  width: 40px;
  text-align: center;
  border: none;
  background: transparent;
  font-size: 15px;
}
.jishi {
  color: #9e9fa0;
  font-size: 15px;
}
.u-f-ac {
  display: flex;
  align-items: center;
}
.u-f-c {
  justify-content: center;
}
.u-f-ajsb {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.u-f-ajc {
  display: flex;
  justify-content: center;
  align-items: center;
}
.icon-row {
  width: 130px;
}
</style>